package com.shortUrl.starter.verticle;

import com.shortUrl.starter.bean.ShortUrl;
import com.shortUrl.starter.util.DecimalConversionUtils;
import com.shortUrl.starter.util.LoadConfigUtils;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;

//短链实现的核心原理：利用url的参数存储长路径的映射，
// 1.传入长路径，
// 2.根据长路径做进入的顺序做发号器，此发号器的地址标识为十进制，
// 3.十进制转换62进制，然后输出，重定向

public class HttpVerticle extends AbstractVerticle {

    @Override
    public void start() throws Exception {
        System.out.println("进入http连接");

        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());

        router.get("/:shortUrlKey").handler(this::handleRedirect);
        router.get("/").handler(this::apiList);
        router.get("/api/create").handler(this::handleCreateShortUrl);
        router.get("/static/*").handler(StaticHandler.create());
        router.get("/favicon.ico").handler(request->{
            // if(request.iss)
            request.end("无视");
        });


        vertx.createHttpServer().requestHandler(router).listen(8081,result -> {
            System.out.println(result);
            if (result.succeeded()) {
                System.out.println("WEB 服务器启动成功！port: " + result.result().actualPort());
            } else {
                System.out.println("WEB 服务器启动失败！case: " + result.cause().getMessage());
            }
        });

    }



    @Override
    public void stop() throws Exception {
        super.stop();
    }



    private void handleCreateShortUrl(RoutingContext context) {
        String url = context.request().getParam("url");
        JsonObject jsonObject = new JsonObject();
        jsonObject.put("prefix", "ID_");
        EventBus bus = vertx.eventBus();
        bus.<String>request("createId", jsonObject, reply -> {
            String id = reply.result().body();
            String shortU = DecimalConversionUtils.to62(Long.valueOf(id));
            ShortUrl shortUrl = ShortUrl.builder().shortUrl(shortU).longUrl(url).build();
            bus.<String>request("saveBean", JsonObject.mapFrom(shortUrl), saveBeanBack -> {
                bus.request("cashShortUrl", JsonObject.mapFrom(shortUrl));

                if (saveBeanBack.succeeded()) {
                    context.end(LoadConfigUtils.getConfig().getString("currentUrl") + shortU);
                }
                ;
            });
        });
    }

    private void handleRedirect(RoutingContext context) {

        String shortUrlKey = context.pathParam("shortUrlKey");
        EventBus bus = vertx.eventBus();
        bus.<String>request("getLongUrl", shortUrlKey, reply -> {
            if (reply.succeeded()) {
                String srcUrl = reply.result().body();
                System.out.println(srcUrl);
                if (srcUrl != null) {
                    context.response().putHeader("Location", "http://" + srcUrl).setStatusCode(301).end();
                } else {
                    sendError(404, context.response());
                }
            }
            if (reply.failed()) {
                bus.<JsonArray>request("getBean", shortUrlKey, getBeanHandler -> {

                    JsonArray jsonArray = getBeanHandler.result().body();
                    JsonObject Result = jsonArray.getJsonObject(0);
                    context.response().putHeader("Location", "http://" + Result.getString("long_url"))
                            .setStatusCode(301).end();
                    bus.request("cashShortUrl", new JsonObject().put("shortUrl", Result.getString("short_url"))
                            .put("longUrl", Result.getString("long_url")));
                });
            }
        });
    }


    private void apiList(RoutingContext context) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.put("/:shortUrlKey", "去到短链页面");
        jsonObject.put("/api/list", "查看所有redisid");
        jsonObject.put("/api/create?url=", "创建Url");

        context.response().putHeader("content-type", "application/json").end(jsonObject.toBuffer());
    }

    private void sendError(int statusCode, HttpServerResponse response) {
        response.setStatusCode(404).end();
    }

}
